<template>
  <div>
    <!-- 修改用户信息表单 -->
    <button @click="jump('src/page/home/index.html')">返回首页</button>
    <form @submit.prevent="updateUserDetails">
      <p>您的唯一用户编号: {{ userMxg.userId }}</p>
      <label for="userName">用户称呼:</label>
      <input type="text" id="userName" v-model="userMxg.userName"><br>

      <label for="userNameLogin">用户登录名称:</label>
      <input type="text" id="userNameLogin" v-model="userMxg.userNameLogin"><br>

      <label for="userOldPassword">确认旧密码:</label>
      <input type="password" id="userOldPassword" v-model="userOldPassword"><br>

      <label for="userPassword">新密码:</label>
      <input type="password" id="userPassword" v-model="userMxg.userPassword"><br>

      <label for="confirmUserPassword">确认新密码:</label>
      <input type="password" id="confirmUserPassword" v-model="confirmUserPassword"><br>

      <p>当前持有硬币数(积分): {{ userMxg.coin }}</p>

      <label for="mailbox">邮箱信息:<samp>请注意:您更换邮箱之后需要重新验证一次</samp>
      <input type="text" id="mailbox" v-model="userMxg.mailbox"></label>
      <br>
      <verify-email/>
      <label for="sex">用户性别信息:</label>
      <input type="text" id="sex" v-model="userMxg.sex"><br>

      <p>用户权限等级:Lv.{{ userMxg.jurisdiction }}</p>

      <label for="birthday">用户当前生日信息:{{ l }}</label><br>
      <label for="birthday">更改生日信息:</label>
      <input type="date" id="birthday" v-model="userMxg.birthday"><br>

      <p>注册时间: {{ formatDate(userMxg.registerTime) }}</p>

      <label for="userPe">用户手机号:</label>
      <input type="text" id="userPe" v-model="userMxg.userPe"><br>

      <label for="bio">用户简介:</label>
      <input type="text" id="bio" v-model="userMxg.bio" rows="20" cols="60"><br>
      <input type="submit" value="修改">
    </form>
    <div>
      <button @click="showUpdateUserHead = !showUpdateUserHead">点击此处隐藏/显示头像修改页面</button>
      <div v-if="showUpdateUserHead">
        <div>
          <h3>当前使用头像:</h3>
          <img v-if="isNotNull(userMxg.userHeadPortraitUrl)"
               :src="`${globalConst.staticResourceUrl}img/${userMxg.userHeadPortraitUrl}`" alt="图片加载失败">
          <p v-else>您没有设置头像</p>
        </div>
        <h4>更换头像</h4>
        <image-cropping :onUploadSuccess="setUserHead"/>
        <div>
          <button @click="banHead">点击禁用头像</button>
          <p>您当前的状态为:{{ isNull(userMxg.userHeadPortraitUrl) ? '已禁用' : '已启用' }} </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/*
  导入 vue 中需要的响应式 API
*/
import {ref, toRaw} from 'vue'

/*
  导入项目中配置好的 axios 实例、全局状态、用户模型以及响应结果包装类
*/
import axiosInstance from '@utils/axiosInstance.ts'
import {Users} from '@models/User.ts'
import ResponseResult from '@models/ReturnResult.ts'
import {getUser, getUserToken, setUser} from "@stores/localStorage.ts";
import {isNull} from "@utils/stringUtil.ts";
import {globalConst} from "@constants/globalConst.ts";
import {useGlobalConfirm} from "@utils/ConfirmDialogPlugin.js";
import {jump} from "@utils/router.js";
import ImageCropping from "@utils/image-cropping.vue";
import VerifyEmail from "@components/verify-email.vue";
// 是否设置头像
const needUserHead = ref(true)
// 定义响应式变量，用于存储确认密码和旧密码
const confirmUserPassword = ref('')
const userOldPassword = ref('')
const showUpdateUserHead = ref(true)
// 创建一个用户对象
const userMxg = ref(getUser())
let l = '1907-01-01'
//@ts-ignore
userMxg.value.birthday = formatDateForInput(userMxg.value.birthday)
l = formatDateForInput(userMxg.value.birthday)
// 如查看其他用户信息
if (
    isNull(userMxg.value.mailbox) &&
    userMxg.value.hasUserMsg()
    &&
    isNull(userMxg.value.bio)
) {
  // 若信息未初始化，则调用接口进行初始化
  axiosInstance.get(`${globalConst.baseUrl}user/getUserMxg`,
      {
        headers: {
          [globalConst.staticResourceUrl]: getUserToken()
        }
      }
  ).then((res) => {
    const r = ResponseResult.fromApiResponse(res.data)
    if (r.isSuccess()) {
      userMxg.value = Users.fromApiResponse(r.returnResult)
      l = formatDateForInput(userMxg.value.birthday)
      setUser(userMxg.value)
    } else {
      alert('信息获取失败!请稍后再试')
    }
  })
}

// 保存用户初始信息（用于修改时与后端比对）
const oldMailbox = userMxg.value.mailbox
needUserHead.value = isNotNull(userMxg.value.userHeadPortraitUrl)


// 格式化日期（传入日期信息，返回本地化字符串）
function formatDate(date: never) {
  if (!date) return '无时间信息'
  const time = new Date(date)
  return time.toLocaleString()
}

/* ---------------------- 修改用户信息的逻辑 ---------------------- */
// 提交表单时调用的函数，用于更新用户信息
async function updateUserDetails() {
  // 判断新密码与确认密码是否一致
  if (userMxg.value.userPassword !== confirmUserPassword.value) {
    alert('新密码和确认密码不一致')
    return
  }
  if (isNull(userOldPassword.value)) {
    alert('请先输入旧密码!')
    return
  } else if (userOldPassword.value.length < 6 || userMxg.value.userPassword.length < 6) {
    alert('密码不可低于6位!(开头和末尾空格将被忽略)')
    return
  }
  const confirm = useGlobalConfirm()
  const r = await confirm('确定要修改信息吗?', {
    title: '是否确认修改用户信息',
    text: '修改用户信息为:\n' + userMxg.value.toString(),
    trueText: '确认修改',
    falseText: '取消修改'
  })
  if (!r) {
    alert('操作已取消!')
    return
  }
  // 调用后端接口进行用户信息更新
  axiosInstance.post(`${globalConst.baseUrl}user/updateUserMxg`, {
    users: toRaw(userMxg.value),
    oldPassWord: toRaw(userOldPassword.value),
    oldMailbox: oldMailbox,
  }).then((res) => {
    const r = ResponseResult.fromApiResponse(res.data)
    if (r.isSuccess()) {
      userMxg.value = Users.fromApiResponse(r.returnResult)
      setUser(userMxg.value)  // 更新用户信息
      alert('个人信息变更成功')
    } else {
      alert('个人信息变更失败!原因是:' + r.msg)
    }
  })
}

function isNotNull(userHeadPortraitUrl: string | null | undefined): boolean {
  return !(userHeadPortraitUrl === null || userHeadPortraitUrl === undefined || userHeadPortraitUrl === 'null')
}


function formatDateForInput(dateInMilliseconds: any): string {
  if (!dateInMilliseconds) return '1970-01-01'
  const date = new Date(dateInMilliseconds)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

const setUserHead = (response: ResponseResult<string>) => {
  if (response.isSuccess()) {
    userMxg.value.userHeadPortraitUrl = <string>response.returnResult
    setUser(userMxg.value)
    alert('你的头像上传成功了!你的个人首页已更新')
    window.scrollTo({
      top: 0,
      behavior: 'smooth' // 平滑滚动
    })
  }
}

async function banHead() {
  const formData = new FormData()
  const emptyFile = new Blob([], {type: 'application/octet-stream'}); // 空的二进制文件
  const r = useGlobalConfirm()
  const result = await r('确定要禁用头像吗?', {
    title: '是否禁用头像',
    text: '禁用头像后，你的个人首页将不显示你的头像'
  })
  if (!result) {
    return
  }
  formData.append('croppedImage', emptyFile);
  formData.append('banHeadPortrait', 'true');
  axiosInstance.post(`${globalConst.baseUrl}user/setUserMxgOfHead`, formData, {
    headers: {
      [globalConst.tokenName]: getUserToken(),
      'Content-Type': 'multipart/form-data',
    }
  }).then((res) => {
    var r = ResponseResult.fromApiResponse(res.data);
    if (r.isSuccess()) {
      userMxg.value.userHeadPortraitUrl = 'null'
      setUser(userMxg.value)
      alert('你的头像禁用成功了!你的个人首页已更新')
    } else {
      alert('你的头像禁用失败!原因是:' + r.msg)
    }
  })
}
</script>
<style scoped>

/* 返回首页按钮 */
button[onclick*="home"] {
  align-self: flex-start;
  padding: 0.8em 1.6em;
  border-radius: 12px;
  border: 2px solid transparent;
  background: linear-gradient(135deg, var(--accent-blue), var(--accent-blue-light));
  color: var(--text-primary);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 168, 255, 0.3);
  margin-bottom: 1rem;
}

button[onclick*="home"]::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

button[onclick*="home"]:hover::before {
  left: 100%;
}

button[onclick*="home"]:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 168, 255, 0.5);
  border-color: var(--accent-blue-light);
}

/* 表单样式 */
form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  background: rgba(42, 42, 42, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 2rem;
  border: 1px solid rgba(255, 42, 109, 0.2);
  box-shadow: var(--shadow-secondary);
  animation: fadeIn 0.6s ease-out;
}

/* 标签样式 */
label {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  color: var(--text-secondary);
  font-weight: 500;
  font-size: 1em;
  margin-bottom: 0.5rem;
}

/* 输入框样式 */
input[type="text"],
input[type="password"],
input[type="date"] {
  padding: 0.8em 1em;
  border: 2px solid var(--secondary-gray);
  border-radius: 8px;
  background: var(--bg-secondary);
  color: var(--text-primary);
  font-size: 1em;
  transition: all 0.3s ease;
  width: 100%;
  max-width: 400px;
}

input[type="text"]:focus,
input[type="password"]:focus,
input[type="date"]:focus {
  outline: none;
  border-color: var(--primary-purple);
  box-shadow: 0 0 10px rgba(211, 54, 255, 0.3);
}

input::placeholder {
  color: var(--text-muted);
}

/* 多行文本输入 */
input[type="text"][id="bio"] {
  min-height: 100px;
  resize: vertical;
  line-height: 1.5;
}

/* 提交按钮 */
input[type="submit"] {
  padding: 1em 2em;
  border-radius: 12px;
  border: 2px solid transparent;
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  color: var(--text-primary);
  font-size: 1.1em;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: var(--shadow-primary);
  margin-top: 1rem;
  max-width: 200px;
  align-self: center;
}

input[type="submit"]::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

input[type="submit"]:hover::before {
  left: 100%;
}

input[type="submit"]:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-glow);
  border-color: var(--primary-red-light);
}

/* 信息显示段落 */
p {
  color: var(--text-secondary);
  line-height: 1.6;
  margin: 0.5rem 0;
  padding: 0.5rem 0;
}

/* 特殊信息显示（用户ID、硬币数、权限等） */
p:first-of-type,
p:nth-of-type(3),
p:nth-of-type(6),
p:nth-of-type(8) {
  color: var(--text-primary);
  font-weight: 600;
  background: rgba(255, 42, 109, 0.1);
  padding: 0.8em 1em;
  border-radius: 8px;
  border-left: 4px solid var(--primary-red);
  margin: 0.8rem 0;
}

/* 邮箱提示信息 */
p:nth-of-type(5) {
  color: var(--accent-blue);
  background: rgba(0, 168, 255, 0.1);
  padding: 0.6em 1em;
  border-radius: 8px;
  border-left: 4px solid var(--accent-blue);
  font-size: 0.9em;
  margin: 0.5rem 0;
}

/* 头像管理区域 */
div > div:last-child {
  background: rgba(42, 42, 42, 0.6);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 2rem;
  border: 1px solid rgba(255, 42, 109, 0.2);
  box-shadow: var(--shadow-secondary);
  animation: fadeIn 0.6s ease-out;
}

/* 头像显示/隐藏切换按钮 */
button[onclick*="showUpdateUserHead"] {
  padding: 0.8em 1.6em;
  border-radius: 12px;
  border: 2px solid var(--secondary-gray);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 1.5rem;
  width: 100%;
}

button[onclick*="showUpdateUserHead"]:hover {
  background: var(--secondary-gray-light);
  color: var(--text-primary);
  border-color: var(--primary-purple);
  box-shadow: 0 0 12px rgba(211, 54, 255, 0.3);
}

/* 头像显示区域 */
div[v-if="showUpdateUserHead"] {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

/* 当前头像显示 */
div[v-if="showUpdateUserHead"] > div:first-child {
  text-align: center;
  padding: 1.5rem;
  background: rgba(26, 26, 26, 0.8);
  border-radius: 12px;
  border: 1px solid var(--border-secondary);
}

div[v-if="showUpdateUserHead"] h3 {
  font-size: 1.3em;
  margin-bottom: 1rem;
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 头像图片 */
img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(255, 42, 109, 0.2);
  transition: all 0.3s ease;
  border: 2px solid rgba(255, 42, 109, 0.3);
}

img:hover {
  transform: scale(1.05);
  box-shadow: var(--shadow-glow);
}

/* 无头像提示 */
p[v-else] {
  color: var(--text-muted);
  font-style: italic;
  padding: 2rem;
  text-align: center;
}

/* 头像裁剪组件容器 */
.image-cropping {
  margin: 1rem 0;
}

/* 禁用头像按钮 */
button[onclick*="banHead"] {
  padding: 0.7em 1.4em;
  border-radius: 12px;
  border: 2px solid var(--secondary-gray);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 1rem;
}

button[onclick*="banHead"]:hover {
  background: var(--primary-red);
  color: var(--text-primary);
  border-color: var(--primary-red-light);
  box-shadow: 0 0 10px rgba(255, 42, 109, 0.3);
}

/* 头像状态显示 */
div[v-if="showUpdateUserHead"] > div:last-child p {
  color: var(--text-secondary);
  margin-top: 0.5rem;
  padding: 0.5rem 0;
  font-style: italic;
}

/* 表单分组视觉效果 */
form label:nth-child(2),
form label:nth-child(3),
form label:nth-child(4),
form label:nth-child(5),
form label:nth-child(6) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 1rem;
}

form label:nth-child(9),
form label:nth-child(10),
form label:nth-child(11),
form label:nth-child(12) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  div {
    padding: 1rem;
    gap: 1.5rem;
  }

  form {
    padding: 1.5rem;
  }

  div > div:last-child {
    padding: 1.5rem;
  }

  input[type="text"],
  input[type="password"],
  input[type="date"] {
    max-width: 100%;
  }

  img {
    max-width: 150px;
    max-height: 150px;
  }
}

@media (max-width: 480px) {
  div {
    padding: 0.8rem;
    gap: 1rem;
  }

  form {
    padding: 1rem;
    gap: 1rem;
  }

  div > div:last-child {
    padding: 1rem;
  }

  input[type="submit"] {
    max-width: 100%;
    padding: 0.8em 1.5em;
  }

  button[onclick*="home"] {
    align-self: stretch;
    text-align: center;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 验证邮箱组件样式 */
verify-email {
  margin: 1rem 0;
  padding: 1rem;
  background: rgba(0, 168, 255, 0.1);
  border-radius: 8px;
  border-left: 4px solid var(--accent-blue);
}

/* 生日标签特殊样式 */
label[for="birthday"]:first-of-type {
  color: var(--text-primary);
  font-weight: 600;
  margin-bottom: 0.5rem;
}

label[for="birthday"]:last-of-type {
  margin-top: 0.5rem;
}
</style>
